/* eslint-disable eqeqeq */
import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import XLSX from 'xlsx';
import { subInvoke } from '@/utils/subprocess';
const path = require('path');
import { ReadFile } from '@/utils/tool'

const user = {
  namespaced: true,
  state: {
    token: sessionStorage.getItem('token'),
    userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
    name: '',
    avatar: '',
    roles: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      sessionStorage.setItem('token', token);
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_USERINFO: (state, paylod) => {
      state.userInfo = paylod;
      sessionStorage.setItem('userInfo', JSON.stringify(paylod));
    }
  },

  actions: {
    // 登录
    async Login({ commit, rootState }, form) {
      // const base = rootState.app.static;
      // const filePath = path.join(base, 'user.xlsx'); // 指定 Excel 文件路径
      // const workbook = XLSX.readFile(filePath);
      // const sheetName = workbook.SheetNames[0]; // 假设只有一个工作表
      // const worksheet = workbook.Sheets[sheetName];
      // const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      // const item = jsonData.find(v => {
      //   if (v[0] == form.username && v[1] == form.password) {
      //     return true;
      //   }
      // })
      const jsonData = ReadFile();

      if (jsonData.account === form.username && jsonData.password === form.password) {
        return true
      } else {
        return false
      }
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then((response) => {
            const data = response.data;
            if (data.roles && data.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', data.roles);
            } else {
              reject('getInfo: roles must be a non-null array !');
            }
            commit('SET_NAME', data.name);
            commit('SET_AVATAR', data.avatar);
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async LogOut({ commit, state }) {
      commit('SET_TOKEN', '');
      commit('SET_USERINFO', {
        name: ''
      });
      return;
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        removeToken();
        commit('SET_TOKEN', '');
        resolve();
      });
    },
  },
};

export default user;
